package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 用户业务逻辑层
 * @author Logan.Li
 */
@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    /**
     * 用户登录验证
     * @param username 用户名
     * @param password 明文密码
     * @return 验证成功返回用户信息，失败返回null
     */
    public User authenticate(String username, String password) {
        try {
            // 查找启用状态的用户
            Optional<User> userOpt = userRepository.findByUsernameAndStatus(username, 1);
            
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                System.out.println("找到用户: " + user.getUsername() + ", 数据库密码: " + user.getPassword());
                System.out.println("输入密码: " + password);
                
                // 验证BCrypt加密的密码
                boolean matches = passwordEncoder.matches(password, user.getPassword());
                System.out.println("密码匹配结果: " + matches);
                
                if (matches) {
                    return user;
                }
            } else {
                System.out.println("未找到用户: " + username);
            }
        } catch (Exception e) {
            System.out.println("认证过程中出现异常: " + e.getMessage());
            e.printStackTrace();
        }
        
        return null;
    }
    
    /**
     * 根据用户名查找用户
     */
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    /**
     * 修改用户密码
     * @param username 用户名
     * @param newPassword 新密码（明文）
     * @return 修改成功返回true，失败返回false
     */
    public boolean changePassword(String username, String newPassword) {
        try {
            Optional<User> userOpt = userRepository.findByUsername(username);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                // 使用BCrypt加密新密码
                String encodedPassword = passwordEncoder.encode(newPassword);
                user.setPassword(encodedPassword);
                userRepository.save(user);
                System.out.println("用户 " + username + " 密码修改成功");
                return true;
            } else {
                System.out.println("用户不存在: " + username);
                return false;
            }
        } catch (Exception e) {
            System.out.println("修改密码时出现异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}
